package com.zjj.easyexcel.utils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.enums.WriteDirectionEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.alibaba.excel.write.metadata.fill.FillWrapper;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName EasyExcelUtil
 * @Description
 * @Author jay
 * @Date 2021/5/19 10:20
 * @Version 1.0
 */
public class EasyExcelUtil {

    public static void main(String[] args) {
        EasyExcelUtil easyExcelUtil = new EasyExcelUtil();
        easyExcelUtil.testCreateExcelTemplate();
    }

    private List<Map> temList() {
        List<Map> mapList = new ArrayList<>();
        Map map;
        for (int i = 0; i <= 20; i++) {
            map = new HashMap();
            map.put("data", "{dataList.data" + i+"}");
            mapList.add(map);
        }
        return mapList;
    }

    private void testCreateExcelTemplate() {
        // 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替
        // {} 代表普通变量 {.} 代表是list的变量 {前缀.} 前缀可以区分不同的list
        String templateFileName =
                FileUtil.getPath() + "test.xlsx";
        System.out.println(templateFileName);
        String fileName = FileUtil.getPath() + "testTem" + System.currentTimeMillis() + ".xlsx";
        ExcelWriter excelWriter = EasyExcel.write(fileName).withTemplate(templateFileName).build();
        WriteSheet writeSheet = EasyExcel.writerSheet().build();
        FillConfig fillConfig = FillConfig.builder().direction(WriteDirectionEnum.HORIZONTAL).build();
        // 如果有多个list 模板上必须有{前缀.} 这里的前缀就是 data1，然后多个list必须用 FillWrapper包裹
        excelWriter.fill(new FillWrapper("list1", temList()), fillConfig, writeSheet);
        // 别忘记关闭流
        excelWriter.finish();
    }
}
